﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;


public class GameController : MonoBehaviour {

    public GameObject airForce;

    public GameObject soldier;

    private GameStateComponent gameState;

    void Start ()
    {
        if (GameObject.Find("GameState"))
        {
            gameState = GameObject.Find("GameState").GetComponent<GameStateComponent>();
        }
    }
	
	void Update () {
	    if (Input.GetKeyDown(KeyCode.Space))
        {
            airForce.GetComponent<PlaneController>().ToggleControlled();
            soldier.GetComponent<SoldierController>().ToggleControlled();
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
	}

    public void Defeat()
    {
        StartCoroutine(AsyncRestartLevel());
    }

    public IEnumerator AsyncRestartLevel()
    {
        yield return new WaitForSeconds(1);
        RestartLevel();
    }

    public void RestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    public void Victory()
    {
        if (gameState != null)
        {
            int civiliansSaved = GameObject.FindGameObjectsWithTag("Civilian").Length;
            int bestCiviliansSaved = Mathf.Max(gameState.GetCiviliansSaved(gameState.currentLevel), civiliansSaved);
            gameState.SetCiviliansSaved(gameState.currentLevel, bestCiviliansSaved);
        } else
        {
            Debug.Log("No game state loaded");
        }

        StartCoroutine(AsyncBackToTitle());
    }

    public IEnumerator AsyncBackToTitle()
    {
        yield return new WaitForSeconds(0.0f);
        BackToTitle();
    }

    public void BackToTitle()
    {
        SceneManager.LoadScene("Title");
    }
}
